<!DOCTYPE html>
<html lang="en" xmlns:E="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>物业管理主页面</title>

    <script src="js/vue3.js"></script>
    <script src="js/axios-0.18.0.js"></script>
    <script src="js/element-plus.js"></script>
    <script src="js/icons-vue.js"></script>
    <script src="js/zh-cn.js"></script>
    <link rel="icon" href="/2.png" type="image/x-icon">
    <script src="js/axios-interceptor.js"></script>
    <link rel="stylesheet" href="css/index.css"/>

    <style>
        .layout-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            font-family: "Helvetica Neue", Arial, sans-serif;
        }

        /* 顶部区域 */
        .header {
            height: 60px;
            background: #409eff;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
        }

        .header-left {
            display: flex;
            align-items: center;
        }

        .logo {
            height: 40px;
            margin-right: 10px;
        }

        .title {
            font-size: 20px;
            font-weight: bold;
            margin: 0;
        }

        .header-right {
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .username {
            cursor: pointer;
            color: #fff;
            display: flex;
            align-items: center;
        }

        /* 主体区域 */
        .main {
            display: flex;
            flex: 1;
        }

        /* 左侧菜单 */
        .sidebar {
            width: 220px;
            background: #f8f9fa;
            border-right: 1px solid #ddd;
            padding-top: 10px;
        }

        .el-menu {
            border-right: none;
        }

        /* 右侧内容 */
        .content {
            flex: 1;
            background: #fff;
            padding: 10px;
        }

        .content-iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
         .avatar-uploader .el-upload {
             border: 1px dashed var(--el-border-color);
             border-radius: 6px;
             cursor: pointer;
             position: relative;
             overflow: hidden;
             transition: var(--el-transition-duration-fast);
         }

        .avatar-uploader .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .avatar-uploader-icon {
            font-size: 28px;
            color: deeppink;
            width: 178px;
            height: 178px;
            text-align: center;
            background: pink;
        }
        .avatar-uploader .avatar{
            width: 178px;
            height: 178px;
        }

        /*ai样式*/

        .ai-chat-button {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
            width: 60px;        /* 宽度 */
            height: 60px;       /* 高度，保持与宽度一致 */
            padding: 0;         /* 移除内边距，防止按钮拉伸 */
            font-size: 24px;
            border-radius: 50%; /* 正圆 */
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }

        /* 整体抽屉深色主题 */
        .ai-chat-drawer {
            background-color: #121212; /* 抽屉整体背景 */
        }

        /* 抽屉标题栏深色主题 */
        .ai-chat-drawer .el-drawer__header {
            background-color: #1f1f1f; /* 标题栏背景 */
            color: #e5e5e5;             /* 文字颜色 */
            border-bottom: 1px solid #333;
        }

        /* 标题文字颜色 */
        .ai-chat-drawer .el-drawer__title {
            color: #e5e5e5;
        }

        /* 抽屉 body 深色 */
        .ai-chat-drawer .el-drawer__body {
            background-color: #121212;
            padding: 0;
        }

        /* 遮罩层透明度调整，可选 */
        .ai-chat-drawer::v-deep(.el-overlay) {
            background-color: rgba(0, 0, 0, 0.7); /* 半透明黑色遮罩 */
        }

        /* 聊天窗口 */
        .chat-window {
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        /* 消息列表 */
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 12px;
            background-color: #121212;
            color: #e5e5e5;
        }

        /* 单条消息 */
        .chat-message {
            margin-bottom: 12px;
            max-width: 75%;
            padding: 8px 12px;
            border-radius: 16px;
            word-break: break-word;
            font-size: 14px;
        }

        /* 用户消息靠右 */
        .chat-message.user {
            background-color: #2a2a2a;
            color: #ffffff;
            margin-left: auto;
        }

        /* AI消息靠左 */
        .chat-message.ai {
            background-color: #1f1f1f;
            color: #e5e5e5;
            margin-right: auto;
        }

        /* 输入区 */
        .chat-input {
            display: flex;
            gap: 8px;
            padding: 12px;
            border-top: 1px solid #333;
            background-color: #121212;
        }

        /* 输入框样式 */
        .chat-input .el-input__inner {
            background-color: #1e1e1e;
            color: #e5e5e5;
            border: 1px solid #333;
        }

        .chat-input .el-input__inner::placeholder {
            color: #888;
        }

        /* 按钮颜色 */
        .chat-input .el-button--primary {
            background-color: #3a3a3a;
            border-color: #3a3a3a;
            color: #e5e5e5;
        }

        .chat-input .el-button--primary:hover {
            background-color: #505050;
            border-color: #505050;
        }
    </style>

</head>
<body>
<div id="app">
    <div class="layout-container">
        <!-- 顶部区域 -->
        <header class="header">
            <div class="header-left">
                <img class="logo" src="./image/1.png" alt="Logo"/>
                <h2 class="title">蜗牛楼宇管理系统</h2>
            </div>
            <div class="header-right">
                <el-avatar :size="40" :src="user.pic"></el-avatar>

                <el-dropdown>
          <span class="el-dropdown-link username">
            {{ user.username }}
            <el-icon><arrow-down></arrow-down></el-icon>
          </span>
                    <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="messageEdit">个人信息编辑</el-dropdown-item>
                                <el-dropdown-item @click="deleteMsg">注销</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

            </div>
        </header>
        <!--弹窗修改信息-->
        <!-- 添加用户的对话框 -->
        <el-dialog v-model="showDialog" title="添加新用户" width="600px">
            <el-form :model="newUser" label-width="100px" :rules="rules" ref="newUserForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="newUser.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="newUser.password" placeholder="请输入密码"></el-input>
                </el-form-item>
<!--                <el-form-item label="确认密码" prop="confirmPassword">-->
<!--                    <el-input v-model="newUser.confirmPassword" placeholder="请输入密码"></el-input>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="头像URL" prop="pic">-->
<!--                    <el-avatar  v-model="newUser.pic" placeholder="请输入头像URL" :size="40" :src="user.pic"></el-avatar>-->
<!--&lt;!&ndash;                    <el-input v-model="newUser.pic" placeholder="请输入头像URL"></el-input>&ndash;&gt;-->
<!--                </el-form-item>-->

                <el-form-item label="头像">
                    <el-upload
                            class="avatar-uploader"
                            action="/user/uploadImg"
                            :show-file-list="false"
                            :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload"
                    >
                        <img v-if="newUser.pic" :src="newUser.pic" class="avatar"/>
                        <el-icon v-else class="avatar-uploader-icon"><Plus></Plus></el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="备注">
                    <el-input
                            type="textarea"
                            :rows="3"
                            placeholder="请输入备注信息"
                            v-model="newUser.remarks">
                    </el-input>
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showDialog = false">取消</el-button>
                    <el-button type="primary" @click="addUser">确认</el-button>
                </span>
            </template>
        </el-dialog>


        <!-- 内容区域 -->
        <div class="main">
            <!-- 左侧菜单 -->
            <aside class="sidebar">
                <el-menu default-active="1" class="el-menu-vertical-demo">
                    <el-sub-menu v-for="m1 in menus" :index="m1.sort">
                        <template #title>{{m1.pname}}</template>
                        <el-menu-item v-for="m2 in m1.children" :index="m2.sort">
                            <el-link :href="m2.url" target="contentFrame">{{m2.pname}}</el-link>
                        </el-menu-item>
                    </el-sub-menu>
                </el-menu>
            </aside>

            <!-- 右侧内容 iframe -->
            <section class="content">
                <iframe name="contentFrame" class="content-iframe" src="/pages/welcome.html"></iframe>
            </section>
        </div>
    </div>
<!--    智能客服-->

    <div>
        <!-- AI客服悬浮按钮 -->
        <el-button
                class="ai-chat-button"
                type="primary"
                @click="toggleChat"
        >AI客服
        </el-button>

        <el-drawer v-model="drawer" title="AI客服" :with-header="true" size="400px" class="ai-chat-drawer">
            <div class="chat-window">
                <!-- 消息列表 -->
                <div class="chat-messages" ref="messagesContainer">
                    <div v-for="(msg, index) in messages" :key="index" :class="['chat-message', msg.from]">
                        <span>{{ msg.content }}</span>
                    </div>
                </div>

                <!-- 输入区 -->
                <div class="chat-input">
                    <el-input
                            v-model="userInput"
                            placeholder="请输入消息"
                            size="small"
                            @keyup.enter="sendMessage"
                    ></el-input>
                    <el-button type="primary" size="small" @click="sendMessage">发送</el-button>
                </div>
            </div>
        </el-drawer>
    </div>

</div>

<script>
    const {createApp, ref, reactive, onMounted, onUpdated,nextTick} = Vue;
    const {ElMessage, ElMessageBox} = ElementPlus;
    const app = createApp({

        setup() {
            const showDialog = ref(false)
            const newUser = ref({})
            const messageEdit = () => {
                axios.get(`/user/getUserById/${user.value.id}`)
                    .then(resp => {
                        console.log(resp.data)
                        newUser.value = resp.data.data;
                        showDialog.value = true; // 显示弹窗
                    })
                    .catch(error => {
                        ElMessage.error(error.response.data.msg);
                    })
            }
            const user = ref({})
            const getMassage = () => {
                axios.get("/user/request").then(resp => {
                    console.log(resp.data)
                    user.value = resp.data.data
                })
            }

            const menus=ref([])
            const getAllMenus = () => {
                axios.get("/permission/getAllMenuPerms").then(resp => {
                    console.log(resp.data)
                    menus.value = resp.data.data
                })
            }
            onMounted(() => {
                // 模拟API调用延迟
                getMassage();
                getAllMenus();
            });

// 删除
            const deleteMsg=()=>{
                ElMessageBox.confirm(`确定要注销用户吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',

                }).then(() => {
                    // let mid = row.buildingId;
                    axios.delete(`/user/deleteMsg`).then(resp => {
                        ElMessage.success(resp.data.msg);
                        window.location.href="/login.html"
                    }).catch(error => {
                        ElMessage.error(error.response.data.msg);
                    })
                })
                    .catch(() => {
                        ElMessage({
                            type: 'info',
                            message: '取消删除',
                        })
                    })
            }
            const addUser = () => {
                updateAllMsg();
            }
            //修改
            const updateAllMsg = () => {
                axios.put("/user/updateAllUser", newUser.value).then(resp => {
                    // 判断resp.data 是否大于1，如果大于1 则修改成功，刷新页面，关闭弹窗
                    if (resp.data.code === 200) {
                        console.log("data:"+ resp.data)
                        data(resp.data.data);
                    } else {
                        ElMessage.error(resp.data.msg)
                    }
                })
            }
            const data = (msg) => {
                ElMessage.error(msg);
                getMassage();
                newUser.value = {}
                showDialog.value = false
            }
            const newUserForm = ref(null)
            // const checkPassword=(rule,value,cb)=>{
            //     if(value!==newUser.value.password){
            //         cb(new Error('两次输入不一致'))
            //
            //     }else{
            //         cb();
            //     }
            // }

            const rules =({
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    // {min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur'},
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    // {pattern:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/,message: '密码必须为6-12位数字组合',trigger: 'blur'}
                ],
                remarks: [
                    {required: true, message: '请输入备注', trigger: 'blur'},
                ],
            })

            const handleAvatarSuccess= (response) => {
                newUser.value.pic = response.data//回显
            }

            const beforeAvatarUpload= (rawFile) => {
                if (rawFile.type !== 'image/jpeg'&& rawFile.type !== 'image/jpg'&& rawFile.type !== 'image/png') {
                    ElMessage.error('上传的图片或格式不正确')
                    return false
                } else if (rawFile.size / 1024 / 1024 > 2) {
                    ElMessage.error('上传的照片不超过2MB!')
                    return false
                }
                return true
            }

// 智能客服

            const drawer = ref(false);
            const userInput = ref('');
            const messages = ref([]);
            const toggleChat = () => {
                drawer.value = !drawer.value;
            };
            const messagesContainer = ref(null);

            function sendMessage() {
                if (!userInput.value) return;

                messages.value.push({ from: 'user', content: userInput.value });
                // const eventSource = new EventSource(`/ai/call/${encodeURIComponent(msg)}`);
                // let aiMessage = '';  // 用来逐字显示
                // let messageIndex = null; // 记录消息在 messages 数组的索引
                //
                // eventSource.onmessage = function(event) {
                //     if (event.data === "[DONE]") {
                //         eventSource.close();
                //         return;
                //     }
                //
                //     const fullText = event.data;  // 后端发送完整AI回复
                //     if (messageIndex === null) {
                //         // 创建一条 AI 消息
                //         messages.value.push({ from: 'ai', content: '' });
                //         messageIndex = messages.value.length - 1;
                //     }
                //
                //     let charIndex = 0;
                //     const timer = setInterval(() => {
                //         if (charIndex < fullText.length) {
                //             messages.value[messageIndex].content += fullText[charIndex];
                //             charIndex++;
                //             nextTick(() => {
                //                 messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                //             });
                //         } else {
                //             clearInterval(timer);
                //         }
                //     }, 30); // 每个字 30ms，调整速度
                // };
                
                axios.get(`/ai/test1/${userInput.value}`).then(resp=>{

                    setTimeout(() => {
                        messages.value.push({ from: 'ai', content: 'AI 回复: ' + resp.data });
                        nextTick(() => {
                            messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                        });
                    }, 500);
                })



                userInput.value = '';
                nextTick(() => {
                    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
                });
            }

            // const msg = userInput.value;
            //



            return {
                user, getMassage, messageEdit, addUser, showDialog, newUser,deleteMsg,newUserForm,rules,handleAvatarSuccess,beforeAvatarUpload
                ,getAllMenus,menus,drawer,userInput,messages,toggleChat,messagesContainer,sendMessage,
            }
        }
    });
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn
    });
    // 注册 Element Plus 图标
    // for (const [key, component]) {
    //     app.component(key, component);
    // }
    app.mount("#app");
</script>
</body>
</html>